package com.bifrost.admin.controller;

import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.annotation.CurrentStore;
import com.bifrost.common.base.ResponseCode;
import com.bifrost.common.base.ServerResponse;
import com.bifrost.model.ResultModel;
import com.bifrost.model.ro.PromotionRO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.model.vo.PromotionSkuVO;
import com.bifrost.service.AdminPromotionService;
import com.bifrost.service.AdminUserService;
import com.bifrost.service.StoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author wqhe
 */
@RestController
@Api("积分促销活动相关接口")
@RequestMapping("/admin/promotion")
@Slf4j
public class AdminPromotionController {

    @Autowired
    private AdminPromotionService adminPromotionService;
    @Autowired
    AdminUserService userService;
    @Autowired
    StoreService storeService;

    @GetMapping("/page")
    @ApiOperation("分页展示所有促销活动的促销商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCode" , value = "查询条件(商品编码)",dataType = "String" ,paramType = "query"),
            @ApiImplicitParam(name = "productName" , value = "查询条件(商品名称)",dataType = "String" ,paramType = "query"),
            @ApiImplicitParam(name = "startTime" , value = "查询条件(开始时间的左区间)",dataType = "String" ,paramType = "query"),
            @ApiImplicitParam(name = "endTime" , value = "查询条件(结束时间的右区间)",dataType = "String" ,paramType = "query"),
            @ApiImplicitParam(name = "pageCode" , value = "当前页(默认为第一页)" , dataType = "int" , paramType = "query"),
            @ApiImplicitParam(name = "pageSize" , value = "单页显示条数(默认为10个)" ,  dataType = "int" , paramType = "query")
    })
    public ResultModel listPromotion(@CurrentStore Long storeId, String productCode, String productName, String startTime, String endTime, @RequestParam(defaultValue = "1") Integer pageCode, @RequestParam(defaultValue = "10") Integer pageSize){
        try{
            PageVO pageVO = adminPromotionService.list(storeService.getMerchantStore(storeId),productCode,productName,startTime,endTime,pageCode,pageSize);
            if(pageVO != null && !CollectionUtils.isEmpty(pageVO.getRecordList())){
                List<PromotionSkuVO> recordList = pageVO.getRecordList();
                // 按照订单id降序排列
                Collections.sort(recordList, new Comparator<PromotionSkuVO>() {
                    @Override
                    public int compare(PromotionSkuVO promotionSkuVO1, PromotionSkuVO promotionSkuVO2) {
                        if (promotionSkuVO1.getPromotionVO().getId() < promotionSkuVO2.getPromotionVO().getId()) {
                            return 1;
                        }
                        if (promotionSkuVO1.getPromotionVO().getId() .equals( promotionSkuVO2.getPromotionVO().getId())) {
                            return 0;
                        }
                        return -1;
                    }
                });
                return ResultModel.ok().put("pageVO",pageVO);
            }
            return ResultModel.error("没有数据");
        }catch (Exception e){
            log.error("获取促销活动失败，原因：",e);
            return ResultModel.error("出现一些未知错误");
        }
    }

    @PostMapping(value = "/add",consumes = "application/json")
    @ApiOperation("新增促销活动")
    public ServerResponse addPromotion(@CurrentAdmin Long adminId,@CurrentStore Long storeId, @RequestBody @Valid PromotionRO promotionRO){
        try{
            List<String> existSkuIdList = adminPromotionService.save(storeService.getMerchantStore(storeId),promotionRO,userService.findById(adminId));
            if(existSkuIdList == null){
                return ServerResponse.createByErrorMsg("未知错误");
            }
            //当本次促销活动中包含了其他促销活动商品时
            if(existSkuIdList != null && !CollectionUtils.isEmpty(existSkuIdList)){
                return ServerResponse.createByErrorCodeMsgAndData(ResponseCode.DATA_COLLISION.getCode(),"一些商品与其他促销活动存在冲突",existSkuIdList);
            }
            return ServerResponse.createBySuccess("新增促销活动成功");
        }catch (Exception e){
            log.error("新增促销活动失败，原因：",e);
            return ServerResponse.createByErrorMsg("出现一些未知错误");
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation("不分页的展示促销活动")
    public ServerResponse promotionList(@RequestParam(required = false) String type){
        List<PromotionSkuVO> promotionSkuVOList = adminPromotionService.listAll(type);
        if(CollectionUtils.isNotEmpty(promotionSkuVOList)){
            return ServerResponse.createBySuccess(promotionSkuVOList);
        }
        return ServerResponse.createBySuccess();
    }

}
